package com.lottery.common.utils;

import com.alibaba.fastjson.JSON;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.nutz.lang.util.NutMap;

public class XssUtils {
    public static ReQueryResult result = new ReQueryResult();

    /**
     * xss check
     * @param str json String
     * @return
     */
    public static ReQueryResult XssFilltration (String str){
        result = new ReQueryResult();
        NutMap nutMap= JSON.parseObject(str,NutMap.class);
        result.success(Constants.SUCCESS_DESC);
        for(String key:nutMap.keySet()){
            if (!Jsoup.isValid(nutMap.getString(key), Whitelist.none())){
                result.error(Constants.PARAMS_ILLEGAL);
                return result;
            }
        }
        return result;
    }


    public static ReQueryResult XssFilltration2 (String str){
        System.out.println(" XSS str   = "+str);
        result = new ReQueryResult();
            if (!Jsoup.isValid(str, Whitelist.none())){
                result.error(Constants.PARAMS_ILLEGAL);
                return result;
            }
            result.success(Constants.SUCCESS_DESC);
        return result;
    }


    public static void sql_xss_inj(String str) throws MyException {
        NutMap nutMap= JSON.parseObject(str,NutMap.class);
        String inj_str = "and，exec，insert，select，delete，update，chr，mid，master，truncate，char，declare，or";
        String inj_stra[]=inj_str.split("，");
        for(String key:nutMap.keySet()){
            if (!Jsoup.isValid(nutMap.getString(key), Whitelist.none())){
                System.out.println("xss valu is ="+nutMap.getString(key));
                throw new MyException("XSS 防御过滤 key : "+key+"  value : "+nutMap.getString(key));
            }
            if (key.equals("token")){
                continue;
            }
            if (key.equals("openId")&&StringUtils.isNotEmpty(nutMap.getString("loginType"))&&(nutMap.getInt("loginType")==3||
                    nutMap.getInt("loginType")==2)){
                continue;
            }

            if (key.equals("phone")&&StringUtils.isNotEmpty(nutMap.getString("loginType"))&&(nutMap.getInt("loginType")==3||
                    nutMap.getInt("loginType")==4)){
                continue;
            }
            for (int i=0 ; i < inj_stra.length ; i++ ){
                if (nutMap.getString(key).toLowerCase().contains(inj_stra[i])){
                    System.out.println(inj_stra[i]);
                    throw new MyException("SQL注入 防御过滤 stra : "+inj_stra[i]+"  key : "+key+"  value : "+nutMap.getString(key));
                }
            }
        }

    }
}
